package upload

import (
	"bufio"
	"fmt"
	"os"
	"path/filepath"
)

func EnsureDirExist(path string) error {
	dir := filepath.Dir(path)
	exists := IsPathExists(dir)
	if !exists {
		err := os.MkdirAll(dir, os.ModePerm)
		if err != nil {
			return err
		}
	}
	return nil
}

// IsPathExists 判断路径是否存在
func IsPathExists(path string) bool {
	if _, err := os.Stat(path); err != nil {
		return false
	}
	return true
}

// WriteFileWithOsFile 将字符串写入文件
func WriteFileWithOsFile(str, path string) error {
	file, err := os.Create(path)
	if err != nil {
		fmt.Println("create file failed")
	}
	defer file.Close()
	writer := bufio.NewWriter(file)
	writer.WriteString(str)
	writer.Flush()
	return nil
}
